<template>
  <div class="form-layout">
    <!--左侧导航-->
    <div class="nav-left">
      <customAnchor
        :itemList="[
          { name: 'box-base', title: '基础信息' },
          { name: 'box-dtl', title: '消耗明细' },
        ]"
      />
    </div>

    <!--表单区域-->
    <div class="form-right" ref="formRight">
      <div id="box-base" class="box-title">基础信息</div>
      <customForm :data="form" :rules="propRules" ref="editForm" :disabled="propReadonly">
        <template #content>
          <customFormItem
            label="消耗单号" name="useKey" :parent="_self" :form="form"
            disabled
            :config="{defaultValue: '自动获取'}"
          />

          <customFormItem
            label="实物仓库" name="warehouseName" :parent="_self" :form="form"
            :readonly="true" :showSelectIcon="true"
            @focus="utilSelect.warehouse(warehouseChange)"
            :disabled="cpHasDtl"
            help="有明细后不可修改"
          />

          <customFormItem
            label="科室名称" name="deptName" :parent="_self" :form="form"
            :readonly="true" :showSelectIcon="true"
            @focus="utilSelect.dept(deptNameChange)"
            :disabled="cpHasDtl"
          />

          <customFormItem
            label="消耗类型" name="useType" :parent="_self" :form="form" disabled
            :type="constCommon.formItemType.selectDict.name"
            :config="{ dictType: constCommon.dictType.deptUseType }"
          />

          <customFormItem
            label="消耗日期" name="useDate" :parent="_self" :form="form"
            :type="constCommon.formItemType.datePicker.name"
          />

          <customFormItem label="冲红" name="flagUseRedType" :parent="_self" :form="form"
                          :type="constCommon.formItemType.switch.name"
                          :config="{flagValueBoolean: true}" :disabled="cpHasDtl"
          />
          <customFormItem label="操作人" name="userName" :parent="_self" :form="form" disabled  />
          <customFormItem label="金额" name="amount" :parent="_self" :form="form" disabled  />
          <customFormItem
            label="备注" name="remark" :parent="_self" :form="form"
          />
        </template>
      </customForm>

      <div id="box-dtl" class="box-title">消耗明细</div>
      <customTooltip title="扫描条码添加明细" v-show="!propReadonly">
        <template #title>
          <div>
            正常单据，扫描有效库存即可
          </div>
          <div>
            冲红单据，扫描科室冲红库存
          </div>
        </template>
        <template #content>
          <FortenScan
            ref="scanInputDtl"
            propPlaceholder="扫描条码添加明细"
            @after-scan="barCodeScan"
            propType="uniqueCode"
            style="width: 450px;margin-top: 10px;"/>
        </template>
      </customTooltip>
      <data-view
        propViewKey="dept_use_dtl"
        :propInitData="form"
        :propParentData="propParent.viewFormData"
        ref="childDataView"
        :propsDisableDbClick="true"
        :propParentPage="_self"
        :propAutoFetchData="false"
        @extra-button-click="extraButtonClick"
        :propHideFlowSelect="true"
        @afterTableDataChange="afterTableDataChange"
        :propFlowKey="propParent.propFlowKey"
        :propNoEditRow="true"
        :propFilterBtn="propFilterBtn"
      />
    </div>

    <!--冲红明细选择-->
    <tableDrawer
      ref="tableDrawerDtlRed"
      refName="tableDrawerDtlRed"
      viewKey="use_dtl_select"
      :queryWrapper="dtlRedqueryWrapper"
      loadForce
      title="请选择需要冲红的明细数据"
      subtitle="筛选所属物理仓库"
      :widthPer="80"
      :heightPx="-1"
      :widthPx="-1"
    />
  </div>
</template>

<script>
import customAnchor from '@/components/custom/form/customAnchor.vue'

export default {
  data() {
    return {
      form: {},
      viewData: {},
      stockIds: [],
      dtlRedqueryWrapper: null,
    }
  },
  computed: {
    // 是否冲红单据
    cpIsRed() {
      return this.form.flagUseRedType == 1
    },
    // 是否有明细
    cpHasDtl() {
      return this.form.countDtl > 0
    },
  },
  methods: {
    // 科室 选择
    deptNameChange(row) {
      this.$set(this.form, 'deptId', row.id)
      this.$set(this.form, 'deptName', row.name)
    },
    // 加载明细
    loadDtl() {
      if (!this.$refs.childDataView) {
        return
      }
      let $newWrapper = this.$newWrapper()
      if (this.form.id) {
        $newWrapper.eq('use_id', this.form.id)
      } else {
        $newWrapper.ne(1, 1)
      }
      this.stockIds = []
      this.$refs.childDataView.setQueryWrapper($newWrapper)
    },
    //扫码SN或RFID
    barCodeScan(scanValue) {
      this.stockIds = []
      this.$ajax.get(`/wm/stock/getStockListByUniqueCode?uniqueCode=${scanValue}`).then((resp) => {
        let stock = resp.data
        stock.forEach((stock, i) => {
          this.stockIds.push(stock.id)
        })
        if (this.form.warehouseId != stock[0].warehouseId) {
          this.utilMessage.error('消耗仓库和当前仓库不一致,不能消耗!')
          return
        }

        this.saveBatchItem(stock)
      })
    },
    // 实物仓库 选择
    warehouseChange(row) {
      this.$set(this.form, 'deptId', row.deptId)
      this.$set(this.form, 'deptName', row.deptName)
      this.$set(this.form, 'warehouseId', row.warehouseId)
      this.$set(this.form, 'warehouseName', row.warehouseName)
    },

    // 明细 新增、删除、修改后调用
    afterTableDataChange() {
        this.utils.refreshRefs(this)
    },

    // 添加明细
    _saveBatchItem(stockList) {
      this.utilVue.loadShow(true)
      let stockIds = stockList.map(item => {
        if (item.stockId) {
          return item.stockId
        }
        return item.id
      })
      let params = {
        stockIds,
        useId: this.form.id,
        flagUseRedType: this.form.flagUseRedType,
        warehouseId: this.form.warehouseId
      }
      this.$ajax.post('/dept/use_dtl/saveByUseSn', params).then((resp) => {
        this.utilVue.loadHide()
        if (resp.code == 0) {
          this.utilMessage.success(resp.msg)
          this.loadDtl()
          this.afterTableDataChange()
        }
      })
    },

    // 添加明细
    saveBatchItem(stockList) {
      //主单据未保存
      if(this.propParent.cpFormNew) {
        this.propParent.ocAsynSaveViewForm(() => {
          this._saveBatchItem(stockList)
        })
        return
      }
      this._saveBatchItem(stockList)
    },

    // 扩展按钮事件
    extraButtonClick({ button, data, index }) {
      let buttonKey = button.key
      if (buttonKey === 'chooseMaterials') { // 选择耗材
        if (this.cpIsRed) {
          this.dtlRedqueryWrapper = this.$newWrapper()
          this.dtlRedqueryWrapper.eq('warehouseId', this.strings.defaultIfBlank(this.form.warehouseId, '-1'))

          this.$refs.tableDrawerDtlRed.show(this.saveBatchItem, true)
        } else {
          this.utilSelect.stockMore(this.saveBatchItem, this.form.warehouseId, false)
        }
      }
    },


    // 过滤显示按钮
    propFilterBtn(btnList) {
      if (this.propReadonly) {
        return btnList.filter(btn => !['chooseMaterials'].includes(btn.code))
      }
      return btnList
    }

  },
  created() {
    let that = this
    this.$emit('event-register', {
      validate: (callback) => {
        return this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        console.log(' this.form', this.form)

        // 新增，设置默认值
        if (!this.form.id) {
          this.$set(this.form, 'useDate', new Date().format('yyyy-MM-dd'))
          this.$set(this.form, 'userName', this.utils.getCurrentUser().name)
          this.$set(this.form, 'useType', 'MANUAL')
          this.$set(this.form, 'amount', '0')
          this.$set(this.form, 'warehouseId', this.utils.getCurrentUser().warehouseId)
          this.$set(this.form, 'warehouseName', this.utils.getCurrentUser().warehouseName)
          this.$set(this.form, 'deptId', this.utils.getCurrentUser().deptId)
          this.$set(this.form, 'deptName', this.utils.getCurrentUser().deptName)
          if (this.strings.isNotBlank(this.utils.getCurrentWarehouse().warehouseId)) {
            this.$set(this.form, 'warehouseId', this.utils.getCurrentWarehouse().warehouseId)
            this.$set(this.form, 'warehouseName', this.utils.getCurrentWarehouse().warehouseName)
          }
        }

        // 设置switch 元素默认值
        this.$set(this.form, 'flagUseRedType', this.form.flagUseRedType == undefined ? false : this.form.flagUseRedType)
        this.loadDtl()
      },
      afterSave: () => {
      },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => { },
      beforeFlow: (flowButtonKey) => {
        if (this.$refs.childDataView.getRows().length == 0) {
          this.utilMessage.error('消耗明细为空，不允许提交')
          return false
        }
        return true
      },
      afterFlow: (flowButtonKey) => {},
      beforeClose: () => {
        return true
      },
      async afterClick(button, data, viewForm) {
        let {
          key: buttonKey
        } = button
        if (buttonKey == 'preview') {
          let param = {
            'that': that, //当前调用对象
            configList: [ //打印配置，可以多个
              {
                //打印配置
                printBusType: 'deptUse', //打印业务类型，来源print_template.bus_type，同constPrint.busKey
                //主单据数据或者数据查询配置
                formData: that.form, //数据对象
                formDataId: that.form.id,
              }
            ]
          }
          global.utilPrint.openFormPrint(param)
        } else  if (buttonKey == 'printsum') {
          let param = {
            'that': that, //当前调用对象
            configList: [ //打印配置，可以多个
              {
                //打印配置
                printBusType: 'deptUseSum', //打印业务类型，来源print_template.bus_type，同constPrint.busKey
                //主单据数据或者数据查询配置
                formData: that.form, //数据对象
                formDataId: that.form.id,
              }
            ]
          }
          global.utilPrint.openFormPrint(param)
        }
      }
    })
  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object,
    propFlowKey: String
  },
  watch: {},
  components: {
    customAnchor
  },
}
</script>
